<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Designer;
use Illuminate\Http\Request;

class TeamController extends Controller
{

    public function __construct()
    {
        $this->middleware('grant:team');
    }

    /**
     * 进入设计师列表页面
     */
    public function getDesignerList()
    {
        return view('admin/team/designer_list');
    }

    /**
     * 获取设计师列表
     */
    public function getDesignerRows()
    {
        $data = Designer::where('status', 1)->get();
        return $this->response($data);
    }

    /**
     * 获取设计师分页列表
     */
    public function getDesignerPageRows(Request $request)
    {
        $kw = strval($request->input('kw'));
        $page = toLimitLng($request->input('page'), 1);
        $limit = toLimitLng($request->input('limit'), 1);
        $offset = ($page - 1) * $limit;

        $query = Designer::where('realname', 'LIKE', '%' . $kw . '%');
        $total_rows = $query->count();
        $rows = $query->orderBy('id', 'ASC')->skip($offset)->take($limit)->get();
        foreach ($rows as $row) {
            $row->headimg = empty($row->headimg) ? '' : asset($row->headimg);
        }
        $data['rows'] = $rows;

        $data['total_rows'] = $total_rows;
        $data['page_count'] = ceil($total_rows / $limit);
        $data['page'] = $page;

        return $this->response($data);
    }

    /**
     * 进入新增设计师页面
     */
    public function getDesignerAdd()
    {
        $data['posts'] = config('components.posts');
        $data['experiences'] = config('components.experiences');
        $data['styles'] = config('components.styles');
        $data['costs'] = config('components.costs');
        return view('admin/team/designer_add', $data);
    }

    /**
     * 新增设计师
     */
    public function postDesignerInsert(Request $request)
    {
        $realname = safe($request->input('realname'), 50);
        $sex = safe($request->input('sex'), 10);
        $post = safe($request->input('post'), 50);
        $experience = safe($request->input('experience'), 50);
        $goodat = implode(',', $request->input('goodat'));
        $cost = safe($request->input('cost'), 50);
        $resume = safe2($request->input('resume'));
        $works = safe2($request->input('works'));
        $idea = safe2($request->input('idea'));
        $fans = intval($request->input('fans'));
        $trusts = intval($request->input('trusts'));
        $views = intval($request->input('views'));
        $status = toLimitLng($request->input('status'), 0, 1);

        if (empty($realname)) {
            return $this->error('参数填写不完整');
        }

        $row = new Designer;
        $data = compact('realname', 'sex', 'post', 'experience', 'goodat', 'cost', 'resume', 'works', 'idea', 'fans', 'trusts', 'views', 'status');
        foreach ($data as $k => $v) {
            $row->$k = $v;
        }
        $row->save();
        return $this->response($row);
    }

    /**
     * 进入编辑设计师页面
     */
    public function getDesignerEdit(Request $request)
    {
        $id = intval($request->input('id'));

        $row = Designer::find($id);
        if (empty($row)) {
            return $this->warning('无效的设计师');
        }
        $data['designer'] = $row;

        $data['posts'] = config('components.posts');
        $data['experiences'] = config('components.experiences');
        $data['styles'] = config('components.styles');
        $data['costs'] = config('components.costs');
        return view('admin/team/designer_edit', $data);
    }

    /**
     * 修改设计师信息
     */
    public function postDesignerUpdate(Request $request)
    {
        $id = intval($request->input('id'));
        $row = Designer::find($id);
        if (empty($row)) {
            return $this->error('无效的设计师');
        }

        if ($request->exists('realname')) {
            $row->realname = safe($request->input('realname'), 50);
        }
        if ($request->exists('sex')) {
            $row->sex = safe($request->input('sex'), 10);
        }
        if ($request->exists('post')) {
            $row->post = safe($request->input('post'), 50);
        }
        if ($request->exists('experience')) {
            $row->experience = safe($request->input('experience'), 50);
        }
        if ($request->exists('goodat')) {
            $row->goodat = implode(',', $request->input('goodat'));
        }
        if ($request->exists('cost')) {
            $row->cost = safe($request->input('cost'), 50);
        }
        if ($request->exists('resume')) {
            $row->resume = safe2($request->input('resume'));
        }
        if ($request->exists('works')) {
            $row->works = safe2($request->input('works'));
        }
        if ($request->exists('idea')) {
            $row->idea = safe2($request->input('idea'));
        }
        if ($request->exists('fans')) {
            $row->fans = intval($request->input('fans'));
        }
        if ($request->exists('trusts')) {
            $row->trusts = intval($request->input('trusts'));
        }
        if ($request->exists('views')) {
            $row->views = intval($request->input('views'));
        }
        if ($request->exists('status')) {
            $row->status = toLimitLng($request->input('status'), 0, 1);
        }
        if ($row->save()) {
            return $this->response($row);
        }
        return $this->error('操作失败');
    }

    /**
     * 上传设计师头像
     */
    public function postUploadHeadimg(Request $request)
    {
        $id = intval($request->input('id'));
        $file = $_FILES['pic'];

        $errorCode = $file['error'];
        if ($errorCode !== UPLOAD_ERR_OK) {
            return $this->error($errorCode);
        }

        $type = exif_imagetype($file['tmp_name']);
        if ($type === false) {
            return $this->error('无效的图片文件');
        }
        if (!in_array($type, [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG])) {
            return $this->error('无效的图片格式');
        }

        $target_path = 'upload/' . date('Y/m/d/');
        $targetPath = public_path() . DIRECTORY_SEPARATOR . $target_path;
        if (!is_dir($targetPath)) {
            if (!mkdir($targetPath, 0777, 1)) {
                return $this->error('无法建立上传目录');
            }
        }

        $new_filename = uniqid(mt_rand()) . image_type_to_extension($type);
        $result = move_uploaded_file($file['tmp_name'], $targetPath . $new_filename);
        if ($result === false) {
            return $tis->error('保存文件失败');
        }
        $image = $target_path . $new_filename;

        $row = Designer::find($id);
        file_exists($row->headimg) and unlink($row->headimg);
        $row->headimg = $image;
        if ($row->save()) {
            return $this->response(asset($image));
        }
        return $this->error('Operation Failed.');
    }

    /**
     * 删除设计师头像
     */
    public function postRemoveHeadimg(Request $request)
    {
        $id = intval($request->input('id'));
        $row = Designer::find($id);
        file_exists($row->headimg) and unlink($row->headimg);
        $row->headimg = '';
        $row->save();
        return $this->response($id);
    }

    /**
     * 删除设计师
     */
    public function postDesignerDelete(Request $request)
    {
        $id = intval($request->input('id'));
        $row = Designer::find($id);
        if (empty($row)) {
            return $this->error('无效的记录');
        }
        file_exists($row->headimg) and unlink($row->headimg);
        $row->delete();
        return $this->response($id);
    }

}
